import { login, logout } from '@/api/user'
import { getToken, removeToken, setMES_PAD_CompInfo, setToken } from '@/utils/auth'
import request from '@/utils/request'
const getDefaultState = () => {
  return {
    data: {},
    token: getToken(),
    // 公司信息
    MES_PAD_CompInfo: localStorage.getItem('MES_PAD_CompInfo')
      ? JSON.parse(localStorage.getItem('MES_PAD_CompInfo'))
      : null || {
        compName: undefined,
        userId: undefined,
        userName: undefined
      },
    userInfo: []
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  MES_PAD_CompInfo: (state, MES_PAD_CompInfo) => {
    setMES_PAD_CompInfo(MES_PAD_CompInfo)
    state.MES_PAD_CompInfo = MES_PAD_CompInfo
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo.length
      ? userInfo
      : [
        {
          id: state.MES_PAD_CompInfo.userId,
          name: state.MES_PAD_CompInfo.userName
        }
      ]
  }
}

const actions = {
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      // removeToken()
      login(userInfo)
        .then(response => {
          const { data } = response
          const { logo, compName, userName, userId } = data.data
          commit('SET_TOKEN', data.data.accessToken)
          setToken(data.data.accessToken) // 保存token
          // 保存公司信息
          commit('MES_PAD_CompInfo', {
            logo: logo,
            compName: compName,
            userName: userName,
            userId: userId
          })
          setTimeout(() => {
            resolve(data)
          }, 1000)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  setToken ({ commit }, compInfo) {
    return new Promise(resolve => {
      commit('SET_TOKEN', compInfo.accessToken)
      setToken(compInfo.accessToken)
      commit('MES_PAD_CompInfo', compInfo)
      resolve()
    })
  },
  // user logout
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (logout) {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resolve()
      }
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  /** 获取所有人员 */
  getAllUser ({ commit }) {
    return new Promise((resolve, reject) => {
      request.get('/dobo-user/user/getAllUser').then(res => {
        if (res.data.code === 200) {
          commit('SET_USER_INFO', res.data.data)
          resolve()
        } else {
          commit('SET_USER_INFO', [])
        }
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
